home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 4434 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.5 KB

  1. Path: keats.ugrad.cs.ubc.ca!not-for-mail
  2. From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: a question on "return"
  5. Date: 4 Feb 1996 08:08:25 -0800
  6. Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
  7. Message-ID: <4f2llpINNlve@keats.ugrad.cs.ubc.ca>
  8. References: <4f2ipq$kaf@srvr1.engin.umich.edu>
  9. NNTP-Posting-Host: keats.ugrad.cs.ubc.ca
  10.  
  11. In article <4f2ipq$kaf@srvr1.engin.umich.edu>,
  12. Chih-Jen Lin <cjlin@news-server.engin.umich.edu> wrote:
  13. >In C, usually we treat 1 as true and 0 as false.
  14. >However, we usually use return(0) after normal end of an int
  15. >function and return(1) when some errors happen.
  16. >Can some one tell me why we return a false value after normal 
  17. >end of a function ?
  18.  
  19. 1.    So you can have a concise, positive test for a failure:
  20.  
  21.     if (myfunc()) {
  22.         /* handle failure */
  23.     }
  24.  
  25.     instead of
  26.  
  27.     if (!myfunc()) {
  28.         /* handle failure */
  29.     }
  30.  
  31. 2.    There are usually(*) more ways to fail than to succeed. Zero
  32.     is unique, non-zero "true" values are abundant. Hence you can use 1 (or
  33.     -1) for one kind of failure, 2 for another and so forth, enabling an
  34.     expression like this:
  35.  
  36.     switch(myfunc()) {
  37.     case -1:
  38.         /* this error */
  39.         break;
  40.     case -2:
  41.         /* that error */
  42.         break;
  43.     case 0:
  44.         /* success */
  45.         break;
  46.     default:
  47.         /* weird */
  48.         break;
  49.     }
  50.  
  51. (*)    Of course, operating system calls like read() have many ways to
  52.     succeed, because they sometimes return a result like the count of bytes
  53.     read. In such a case, negative results can indicate failure, and
  54.     non-negative results success.
  55. -- 
  56.  
  57.